package com.wyh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyh.common.response.PageInfo;
import com.wyh.common.result.R;
import com.wyh.common.util.StringUtil;
import com.wyh.entity.MsgChatRoom;
import com.wyh.mapper.MsgChatRoomMapper;
import com.wyh.request.MsgChatRoomRequest;
import com.wyh.service.IMsgChatRoomService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 群组业务层处理
 *
 * @author WangYuHang
 * @date 2024-03-08
 */
@Slf4j
@Service
@AllArgsConstructor
public class MsgChatRoomServiceImpl implements IMsgChatRoomService {

    private final MsgChatRoomMapper baseMapper;

    @Override
    public R<List<MsgChatRoom>> queryList() {
        //模拟当前用户位666666

        String userId = "666666";
        List<MsgChatRoom> msgChatRooms = baseMapper.selectList(Wrappers.lambdaQuery(MsgChatRoom.class).like(MsgChatRoom::getMemberList, userId));
        return R.success(msgChatRooms);
    }

    @Override
    public R<String> moveOutChatRoom(String chatRoomId, String userId) {
        if (StringUtil.isEmpty(chatRoomId) || StringUtil.isEmpty(userId)){
            R.error("参数错误");
        }
        MsgChatRoom msgChatRoom = baseMapper.selectOne(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId, chatRoomId));
        String memberList = msgChatRoom.getMemberList();
        if (memberList.length()>7){
            String[] split = memberList.split(",");
            List<String> list = Arrays.asList(split);
            //判断是否在群里
            if (list.contains(userId)) {
                list.remove(userId);
                String newMember = String.join(",", list);
                //更新
                msgChatRoom.setMemberList(newMember);
                baseMapper.updateById(msgChatRoom);
                R.success("移出成功！");
            }
        }
        return R.error("还没有群成员！");
    }

    @Override
    public R<String> addPerson(String chatRoomId, String userId) {
        MsgChatRoom msgChatRoom = baseMapper.selectOne(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId, chatRoomId));
        String memberList = msgChatRoom.getMemberList();

        //将新用户加入群聊
        String newMemberList = memberList+","+userId;
        msgChatRoom.setMemberList(newMemberList);
        baseMapper.updateById(msgChatRoom);
        return R.success("加群成功！");
    }

    @Override
    public R<MsgChatRoom> queryById(String chatRoomId) {
        //根据id查找群聊
        if (StringUtil.isEmpty(chatRoomId)){
            R.error("未找到群聊");
        }

        MsgChatRoom msgChatRoom = baseMapper.selectOne(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId, chatRoomId));
        return R.success(msgChatRoom);
    }
    /**
     * 判断群聊是否已满
     * @param chatRoomId
     * @return
     */
    @Override
    public Boolean queryIsMax(String chatRoomId) {
        MsgChatRoom msgChatRoom = baseMapper.selectOne(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId, chatRoomId));
        String memberList = msgChatRoom.getMemberList();
        //说明大于1人
        if (memberList.length() > 7) {
            String[] split = memberList.split(",");
            if (split.length == 300) {
                return true;
            }
        }
        return false;
    }
    /**
     * 判断用户是否在群里
     * @param userId
     * @param chatRoomId
     * @return
     */
    @Override
    public Boolean queryIsExist(String userId, String chatRoomId) {
        MsgChatRoom msgChatRoom = baseMapper.selectOne(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId, chatRoomId));
        String memberList = msgChatRoom.getMemberList();
        if (memberList.length()>7){
            String[] split = memberList.split(",");
            List<String> list = Arrays.asList(split);
            //判断是否在群里
            if (list.contains(userId)) {
                return true;
            }
        }else {
            if (memberList.equals(userId)){
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否超出创建群聊限制
     * @param userId
     * @return
     */
    @Override
    public Boolean queryIsOutChatRoomCount(String userId) {
        //用户id
        Long aLong = baseMapper.selectCount(Wrappers.lambdaQuery(MsgChatRoom.class)
                .eq(MsgChatRoom::getRoomOwner, userId));
        if (aLong==600){
            return true;
        }
        return false;
    }

    @Override
    public R<String> dissolveChatRoom(String chatroomId) {
        if (StringUtil.isEmpty(chatroomId)){
            R.error("参数错误");
        }
        baseMapper.delete(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId,chatroomId));
        return R.success("解散成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MsgChatRoom add(MsgChatRoomRequest request) {
        //创建之前需要判断创建的群是否已达到上限
        //前端传入第一个人member 不需要加逗号
        MsgChatRoom build = MsgChatRoom.builder().build();
        BeanUtils.copyProperties(request,build);
        MsgChatRoom entity = MsgChatRoom.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Integer> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(MsgChatRoomRequest request) {
        MsgChatRoom entity = MsgChatRoom.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0 ;
    }

    @Override
    public MsgChatRoom getById(String id) {
        MsgChatRoom msgChatRoom = baseMapper.selectOne(Wrappers.lambdaQuery(MsgChatRoom.class).eq(MsgChatRoom::getChatRoomId,id ));
        return msgChatRoom;
    }

    @Override
    public PageInfo<MsgChatRoom> pageList(MsgChatRoomRequest request) {
        Page<MsgChatRoom> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<MsgChatRoom> query = this.buildWrapper(request);
        IPage<MsgChatRoom> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<MsgChatRoom> list(MsgChatRoomRequest request) {
        LambdaQueryWrapper<MsgChatRoom> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<MsgChatRoom> buildWrapper(MsgChatRoomRequest param) {
        LambdaQueryWrapper<MsgChatRoom> query = new LambdaQueryWrapper<>();

         if (StringUtils.isNotBlank(param.getMemberList())){
               query.like(MsgChatRoom::getMemberList ,param.getMemberList());
        }
         if (StringUtils.isNotBlank(param.getDisplayNameList())){
               query.like(MsgChatRoom::getDisplayNameList ,param.getDisplayNameList());
        }
         if (StringUtils.isNotBlank(param.getRoomOwner())){
               query.like(MsgChatRoom::getRoomOwner ,param.getRoomOwner());
        }
         if (StringUtils.isNotBlank(param.getSetDisplayName())){
               query.like(MsgChatRoom::getSetDisplayName ,param.getSetDisplayName());
        }
         if (StringUtils.isNotBlank(param.getChatRoomNick())){
               query.like(MsgChatRoom::getChatRoomNick ,param.getChatRoomNick());
        }
         if (StringUtils.isNotBlank(param.getChatRoomAvatar())){
               query.like(MsgChatRoom::getChatRoomAvatar ,param.getChatRoomAvatar());
        }
         if (StringUtils.isNotBlank(param.getChatRoomSignature())){
               query.like(MsgChatRoom::getChatRoomSignature ,param.getChatRoomSignature());
        }
         if (StringUtils.isNotBlank(param.getChatRoomRemark())){
               query.like(MsgChatRoom::getChatRoomRemark ,param.getChatRoomRemark());
        }
         if (StringUtils.isNotBlank(param.getIsInvite())){
               query.like(MsgChatRoom::getIsInvite ,param.getIsInvite());
        }
        if (param.getCreateUserId() != null){
               query.eq(MsgChatRoom::getCreateUserId ,param.getCreateUserId());
        }
        if (param.getUpdateUserId() != null){
               query.eq(MsgChatRoom::getUpdateUserId ,param.getUpdateUserId());
        }
        return query;
    }

}
